<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
      <!-- 选择商品分类区域 -->
      <el-form>
        <el-form-item label="选择商品分类：">
          <el-cascader
            v-model="value"
            :options="selectCate"
            :props="selectCateProps"
            clearable
            @change="selectChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 参数区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClickTab">
        <!-- 动态参数部分 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="small" @click="addParamsDialog = true">添加参数</el-button>
          <el-table :data="TableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="deleteTag(scope.row, index)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible===scope.row.attr_id"
                  v-model="addNewParams"
                  ref="saveNewParams"
                  size="small"
                  @keyup.enter.native="addConfirm(scope.row)"
                  @blur="addConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row.attr_id)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-search" @click="editDialog(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性部分 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="small" @click="addParamsDialog = true">添加属性</el-button>
          <el-table :data="TableData" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="deleteTag(scope.row, index)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible===scope.row.attr_id"
                  v-model="addNewParams"
                  ref="saveNewParams"
                  size="small"
                  @keyup.enter.native="addConfirm(scope.row)"
                  @blur="addConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row.attr_id)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-search" @click="editDialog(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的弹出框 -->
    <el-dialog
      :title="activeName == 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addParamsDialog"
      width="50%"
      :before-close="addClose"
    >
      <el-form :model="addParamsForm" :rules="ParamsRules" ref="addRuleForm" label-width="100px">
        <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性'" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsNo">取 消</el-button>
        <el-button type="primary" @click="addParamsOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数的弹出框 -->
    <el-dialog :title="activeName == 'many' ? '修改动态参数' : '修改静态属性'" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editParamsForm" :rules="ParamsRules" ref="editRuleForm" label-width="100px">
        <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性'" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getGoodsListApi,
  getParamsApi,
  addApi,
  editParamsApi,
  deleteParamsApi
} from "../api/index.js";
import { close } from "fs";
export default {
  data: function() {
    return {
      selectCate: [],
      value: [],
      selectCateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      activeName: "many",
      // 获取参数列表是需要的id参数
      paramsId: 0,
      // 动态/静态参数的数据
      TableData: [],
      // 控制添加的tag切换成input输入框
      inputVisible: "",
      addNewParams: "",
      // 添加动态参数接口需要的数据
      paramsInfo: {
        attr_name: "",
        attr_sel: "",
        attr_vals: ""
      },
      // 控制添加参数的弹出框显示与隐藏
      addParamsDialog: false,
      // 添加表单数据
      addParamsForm: {
        attr_name: "",
        attr_sel: "",
        attr_vals: ""
      },
      // 表单验证
      ParamsRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      // 编辑参数的弹出框显示与隐藏
      editDialogVisible: false,
      // 编辑表单数据
      editParamsForm: {
        attr_id: "",
        attr_name: "",
        attr_sel: "",
        attr_vals: ""
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await getGoodsListApi();
      if (res.meta.status !== 200) return this.$message.error("数据获取失败");
      this.selectCate = res.data;
      // console.log(this.selectCate);
    },
    // 切换only 和 many 值 来获取相对应的数据
    handleClickTab() {
      this.getParamsData(this.activeName);
      // this.deleteTag(row, index, this.activeName)
    },
    // 获取动态/静态参数数据
    async getParamsData(sel) {
      this.paramsId = this.value[this.value.length - 1];
      const { data: res } = await getParamsApi(this.paramsId, sel);
      // console.log(res.data);
      res.data.forEach(value => {
        value.attr_vals = value.attr_vals.split(",");
      });
      if (this.activeName == "many") {
        this.TableData = res.data;
      } else {
        this.TableData = res.data;
      }
    },
    // 监听下拉框的change事件
    async selectChange() {
      this.getParamsData(this.activeName);
    },
    // 监听静态/动态添加标签的点击事件，切换input输入框
    showInput(id) {
      this.inputVisible = id;
      this.$nextTick(_ => {
        this.$refs.saveNewParams.$refs.input.focus();
      });
    },
    // 添加动态/静态参数的标签的监听事件
    async addConfirm(row) {
      if (!this.addNewParams) return;
      this.paramsInfo.attr_name = row.attr_name;
      this.paramsInfo.attr_sel = row.attr_sel;
      row.attr_vals.push(this.addNewParams);
      // 进行去重 防止添加重复的
      row.attr_vals = [...new Set(row.attr_vals)];
      this.paramsInfo.attr_vals = row.attr_vals.join(",");
      const { data: res } = await editParamsApi(
        row.cat_id,
        row.attr_id,
        this.paramsInfo
      );
      this.inputVisible = "";
      this.addNewParams = "";
    },
    // 删除动态/静态参数内的标签
    async deleteTag(row, index) {
      // console.log(row.attr_vals, index);
      row.attr_vals.splice(index, 1);
      this.paramsInfo.attr_vals = row.attr_vals.join(",");
      this.paramsInfo.attr_name = row.attr_name;
      this.paramsInfo.attr_sel = this.activeName;
      const { data: res } = await editParamsApi(
        this.paramsId,
        row.attr_id,
        this.paramsInfo
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
    },
    // 删除动态参数
    async deleteParams(row) {
      const { data: res } = await deleteParamsApi(row.cat_id, row.attr_id);
      if (res.meta.status !== 200) return this.$message.error("删除失败！");
      this.selectChange();
      console.log(res);
    },
    // 添加动态参数和静态属性
    addParamsOk() {
      this.$refs.addRuleForm.validate(async valid => {
        if (!valid) return;
        this.addParamsForm.attr_sel = this.activeName;
        const { data: res } = await addApi(this.paramsId, this.addParamsForm);
        if (res.meta.status !== 201) return this.$message.error("分类创建成功");
        this.getParamsData(this.activeName);
        this.addParamsDialog = false;
        this.$refs.addRuleForm.resetFields();
      });
    },
    addParamsNo() {
      this.$refs.addRuleForm.resetFields();
      this.addParamsDialog = false;
    },
    addClose() {
      this.addParamsNo();
    },
    // 点击显示编辑的弹出框
    editDialog(row) {
      this.editParamsForm.attr_name = row.attr_name
      this.editParamsForm.attr_id = row.attr_id
      this.editDialogVisible = true
    },
    // 编辑动态参数和静态参数
    editParams() {
      this.$refs.editRuleForm.validate(async valid => {
        if(!valid) return
        this.editParamsForm.attr_sel = this.activeName;
        const {data: res} = await editParamsApi(this.paramsId, this.editParamsForm.attr_id, this.editParamsForm)
        if(res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.getParamsData(this.activeName);
        this.editDialogVisible = false;
        this.$refs.editRuleForm.resetFields();
      })
    }
  }
};
</script>

<style lang="less" scoped>
.el-form {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
